﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.FxCop.Sdk;
using System.Collections.ObjectModel;

namespace Community.StaticAnalysis.Reliability.Rules
{
    /// <summary>
    /// Inspects that finally block
    /// </summary>
    public class FinallyBlockVisitor : BinaryReadOnlyVisitor
    {
        #region Fields

        private Collection<Variable> _variableList = new Collection<Variable>();

        #endregion

        #region Constructor

        /// <summary>
        /// creates an instance of this type
        /// </summary>
        public FinallyBlockVisitor()
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the object that are not correctlydisposed
        /// </summary>
        public Collection<Variable> VariableList
        {
            get { return _variableList; }
        }
        #endregion


        /// <summary>
        /// Visits an Expression statment
        /// </summary>
        /// <param name="statement"></param>
        public override void VisitExpressionStatement(ExpressionStatement statement)
        {
            if (statement != null)
            {

                MethodCall call = statement.Expression as MethodCall;

                if (call != null)
                {
                    MemberBinding binding = call.Callee as MemberBinding;

                    if (binding != null)
                    {
                        if (binding.BoundMember.Name.Name == "Dispose")
                        {
                            Variable var = binding.TargetObject as Variable;

                            if (var != null)
                            {
                                if (_variableList.Contains(var))
                                {
                                    _variableList.Remove(var);
                                }
                            }
                        }
                    }

                }
            }

            base.VisitExpressionStatement(statement);
        }
    }
}
